package top.lanscarlos.ashcraft.repository;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import top.lanscarlos.ashcraft.pojo.LogInfo;
import top.lanscarlos.ashcraft.pojo.User;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.repository
 *
 * @author Lanscarlos
 * @since 2022-05-25 14:26
 */
@Repository
public class UserRepository {
    @Autowired
    private SessionFactory sessionFactory;

    /**
     * 插入新的用户数据
     *
     * @return 插入成功返回 true 反之 false
     * */
    public boolean insert(User user) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            session.save(user.getCart());
            session.save(user);
            LogInfo info = new LogInfo(user);
            session.save(info);
            transaction.commit();
            return true;
        } catch (Exception e) {
            if (transaction != null) transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return false;
    }

    /**
     * 保存用户信息
     *
     * @return 保存成功返回 true 反之 false
     * */
    public boolean save(User user) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            session.save(user);
            transaction.commit();
            return true;
        } catch (Exception e) {
            if (transaction != null) transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return false;
    }

}
